import React, { JSX } from 'react';
import { NulDialog, NulCommonOperations, NulFormItem } from '../../components/NulDialog';
import { FormControl, TextField, Autocomplete } from '@mui/material';
import { useAppDispatch } from '../../actions/hooks';
import { CommodityEntry, SupplierEntry, InventoryEntry } from '../../types';
import { inventoryManagementActions } from '../../actions/InventoryManagement';

interface CreateInventoryProps {
  open: boolean;
  onClose: () => void;
  commodityEntries: CommodityEntry[],
  supplierEntries: SupplierEntry[],
  warehouseId: number,
  modifyEntry: InventoryEntry
}

interface CommodityOption {
  label: string;
  id: number;
}

interface SupplierOption {
  label: string;
  id: number;
}

function buildOptions(commodityEntries: CommodityEntry[]): CommodityOption[] {
  if (commodityEntries === undefined || commodityEntries === null) {
    return [];
  }
  const result: CommodityOption[] = [];
  for (let i = 0; i < commodityEntries.length; ++i) {
    result.push({ label: commodityEntries[i].name, id: commodityEntries[i].id });
  }
  return result;
};

function buildSupplierOptions(supplierEntries: SupplierEntry[]): SupplierOption[] {
  if (supplierEntries === undefined || supplierEntries === null) {
    return [];
  }
  const result: SupplierOption[] = [];
  for (let i = 0; i < supplierEntries.length; ++i) {
    result.push({ label: supplierEntries[i].name, id: supplierEntries[i].id });
  }
  return result;
}

function ModifyInventory(props: CreateInventoryProps): JSX.Element {
  const { open, onClose, commodityEntries, supplierEntries, warehouseId, modifyEntry } = props;

  console.log(modifyEntry);

  const commodityOptions = buildOptions(commodityEntries);
  const supplierOptions = buildSupplierOptions(supplierEntries);

  const initalCommodity = commodityOptions.find(value => value.id === modifyEntry.commodityId);
  const initalSupplier = supplierOptions.find(value => value.label === modifyEntry.supplierName);

  const [commodity, setCommodity] = React.useState<CommodityOption | null>(initalCommodity ?? null);
  const [quantity, setQuantity] = React.useState<string>(modifyEntry.quantity.toString());
  const [supplier, setSupplier] = React.useState<SupplierOption | null>(initalSupplier ?? null);

  React.useEffect(() => {
    const commodity = commodityOptions.find(value => value.id === modifyEntry.commodityId);
    if (commodity !== undefined) {
      setCommodity(commodity);
    }
    const supplier = supplierOptions.find(value => value.label === modifyEntry.supplierName);
    if (supplier !== undefined) {
      setSupplier(supplier);
    }
    setQuantity(modifyEntry.quantity.toString());
  }, [modifyEntry]);

  const dispatch = useAppDispatch();

  const clear = () => {
    setCommodity(null);
    setQuantity('');
    setSupplier(null);
  }

  const onModifyClicked = () => {
    if (commodity && supplier) {
      dispatch(inventoryManagementActions.deleteInventory({ warehouseId: warehouseId, id: [modifyEntry.id] }));
      dispatch(inventoryManagementActions.stockInventory({ warehouseId: warehouseId, commodityId: commodity.id, quantity: parseFloat(quantity), supplierId: supplier.id }));
      onClose();
      clear();
    }
  };

  return (
    <NulDialog
      open={open}
      onClose={onClose}
      title='Modify Inventory Entry'
      operations={
        <NulCommonOperations
          onPositiveClicked={onModifyClicked}
          onNegativeClicked={onClose}
          positiveText='Modify'
        />
      }
    >
      <NulFormItem hint='Commodity' component={
        <FormControl fullWidth size='small'>
          <Autocomplete
            options={commodityOptions}
            size='small'
            fullWidth={true}
            getOptionLabel={option => option.label}
            renderInput={(params) => <TextField {...params} />}
            value={commodity}
            onChange={(event, value) => {
              setCommodity(value);
            }}
          />
        </FormControl>
      } />
      <NulFormItem hint='Quantity' component={
        <TextField placeholder='Quantity' fullWidth={true} size='small' value={quantity} onChange={(event) => { setQuantity(event.target.value); }} />
      } />
      <NulFormItem hint='Supplier' component={
        <FormControl fullWidth size='small'>
          <Autocomplete
            options={supplierOptions}
            size='small'
            fullWidth={true}
            getOptionLabel={option => option.label}
            renderInput={(params) => <TextField {...params} />}
            value={supplier}
            onChange={(event, value) => {
              setSupplier(value);
            }}
          />
        </FormControl>
      } />
    </NulDialog>
  );
}

export { ModifyInventory };